<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body>
    <div>
        <button>发送请求</button>
        <button>取消请求</button>
    </div>

    <script>
        const btns=document.querySelectorAll('button');
        //2.声明全局变量
        let cancel=null;
        btns[0].onclick=function(){
            //检测上一次的请求是否完成
            if(cancel!==null){
                //取消上一次请求
                cancel();
            }
            axios({
                method:'GET',
                url:'http://localhost:3000/posts',
                //1.添加对象属性
                cancelToken:new axios.CancelToken(function(c){
                    //3.将 c 的值赋值给 cancel
                    cancel=c;
                })
            }).then(response=>{
                console.log(response);
                //将cancel的值初始化
                cancel=null;
            });
        }

        //取消请求
        btns[1].onclick=function(){
            cancel();
        }
    </script>
</body>
</html>
